package com.plum.admin.common.util;

import cn.hutool.core.bean.BeanUtil;
import com.plum.admin.common.constant.Constant;
import com.plum.admin.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/9/14 16:14
 */
@Component
@Slf4j
public class EmailUtil {

    @Autowired
    private TemplateEngine templateEngine;
    @Async
    public void sendTemplateEmail(String sendTo,String title,String templateName,Object o){
        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
        senderImpl.setHost(Constant.EMAIL_HOST);
        senderImpl.setUsername(Constant.EMAIL_USERNAME);
        senderImpl.setPassword(Constant.EMAIL_PASSWORD);
        Properties prop=new Properties();
        // 服务器进行认证
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.timeout", "20000");
        // 邮箱发送服务器端口,这里设置为465端口
        prop.setProperty("mail.smtp.port", "465");
        prop.setProperty("mail.smtp.socketFactory.port", "465");
        prop.put("mail.smtp.ssl.enable", "true");
        senderImpl.setJavaMailProperties(prop);
        // 发送html邮件
        MimeMessage mailMessage = senderImpl.createMimeMessage();
        MimeMessageHelper messageHelper = null;
        try {
            messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

            messageHelper.setTo(sendTo);
            messageHelper.setFrom(Constant.EMAIL_USERNAME);
            messageHelper.setSubject(title);
            Context context = new Context();
            context.setVariables(BeanUtil.beanToMap(o));
            // 获取模板html代码
            String content = templateEngine.process(templateName, context);
            // true表示HTML格式的邮件
            messageHelper.setText(content, true);
            // 发送邮件
            senderImpl.send(mailMessage);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
            throw new BaseException("发送邮件失败，请检查邮件配置");
        }
    }
}
